package com.wxlgroup.springboot.utils;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.wxlgroup.springboot.commons.Response;
import com.wxlgroup.springboot.entity.User;
import com.wxlgroup.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
 * @auther:wxl
 * @Date:2022/5/24-05-24-18:23
 * @Description:com.wxlgroup.springboot.utils
 * @Version:1.0
 */
@Component
public class TokenUtils {

    @Autowired
    private UserService userService;

    private static UserService userServices;

    @PostConstruct          //在该对象被注入容器时调用此方法
    public void setUserService(){
        userServices=userService;
    }


    public static String genToken(String userId,String sign){
        return JWT.create().withAudience(userId)        //将userId作为载荷保存到token
        .withExpiresAt(DateUtil.offsetHour(new Date(),2))       //token两个小时过期
        .sign(Algorithm.HMAC256(sign));         //以password作为token的密钥
    }


    /*
    获取当前用户的信息，有时候用户可能不携带参数，此方法可以在任何地方进行使用
     */
    public static User getCurrentUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String userId = JWT.decode(token).getAudience().get(0);
        Response response = userServices.queryUserById(Integer.parseInt(userId));
        return (User) response.getResponseData();
    }
}
